package cn.itcast.hotel.listener;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class HotelListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //指定从那个队列消费消息
    @RabbitListener(queues = "hotel.insert.queue")
    public void handleMessage(String msg) throws IOException {
        System.out.println("接收到消息:"+msg);
        //将JSON转换成为对象
        Hotel hotel = JSON.parseObject(msg, Hotel.class);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //将数据更新到es中
        UpdateRequest request = new UpdateRequest("hotel", hotelDoc.getId().toString());
        //更新数据
        request.doc(JSON.toJSONString(hotel),
                XContentType.JSON);
        restHighLevelClient.update(request, RequestOptions.DEFAULT);
    }



}
